﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using CCPnuts.ISkyDiskFileSystem.Interfaces;
using System.Diagnostics;

namespace SkyDiskFileSystem
{
    internal class AutoUpdater
    {
        internal static Thread UpdateThread;

        /// <summary>
        /// This is the collection of all the objects to be update.
        /// </summary>
        internal static volatile List<IUpdatable> TaskList = new List<IUpdatable>();

        /// <summary>
        /// This is the colleciton of all the objects to exit from Monitor
        /// </summary>
        internal static volatile List<object> ExitList = new List<object>();

        internal static void Run()
        {
            UpdateThread = new Thread(() =>
            {
                while (true)
                {
                    while (ExitList.Count > 0)
                    {
                        var item = ExitList.First();
                        Monitor.Exit(item);
                        ExitList.Remove(item);
                    }
                    while (TaskList.Count > 0)
                    {
                        var item = TaskList.First();
                        item.Update();
                        TaskList.Remove(item);
                    }
                    lock (TaskList)
                    {
                        System.Threading.Monitor.Wait(TaskList);
                    }
                }
            });
            UpdateThread.Start();
        }
    }
}
